
//request.js
import axios from "axios";
import router from '../router'
import store from '../store';
import { message } from 'ant-design-vue';

/****** 创建axios实例 ******/
const service = axios.create({
    // baseURL: process.env.BASE_URL,  // api的base_url
    timeout: 5000  // 请求超时时间
});

service.interceptors.request.use(
    config => {
        if (store.state.loginToken) {  // 判断是否存在token，如果存在的话，则每个http header都加上token
            config.data.loginToken = store.state.loginToken;
        }
        return config;
    },
    err => {
        return Promise.reject(err);
    }
);

service.interceptors.response.use(
    response => {  //成功请求到数据 
        //这里根据后端提供的数据进行对应的处理
        if (response.data.code == -1) {
            message.error(response.data.msg);
        }
        if (response.data.code == -105) {
            router.push({
                path: "/login"
            });
        }
        if (response.data.code == -114) {
            message.error(response.data.msg);
        }
        if (response.data.code == -115) {
            message.error(response.data.msg);
        }
        if (response.data.code == -116) {
            message.error(response.data.msg);
        }
        if (response.data.code == -117) {
            message.error(response.data.msg);
        }
        if (response.data.code == -206) {
            message.error(response.data.msg);
        }
        if (response.data.code == -401) {
            message.error(response.data.msg);
        }
        if (response.data.code == -1001) {
            message.error(response.data.msg);
        }
        if (response.data.code == -1002) {
            message.error(response.data.msg);
        }
        if (response.data.code == -1003) {
            message.error(response.data.msg);
        }
        if (response.data.code == -2001) {
            message.error(response.data.msg);
        }
        if (response.data.code == -3001) {
            message.error(response.data.msg);
        }
        return response;
    },
    error => {
        switch (error.response.status) {
            case 400:
                message.error('http错误码400:请求参数格式不正确');
                break;
            case 401:
                message.error('http错误码401:权限不足');
                router.push("/login");
                break;
            case 403:
                message.error('http错误码403:禁止访问');
                break;
            case 404:
                message.error('http错误码404:请求路径错误');
                break;
            case 405:
                message.error('http错误码405:资源被禁止');
                break;
            case 408:
                message.error('http错误码408:请求超时');
                break;
            case 500:
                message.error('http错误码500:服务器异常');
                break;
        }
    }
)

export default service;